import { reqRegisterUser } from "@/api/index"

const state = {
    allUser: JSON.parse(localStorage.getItem('allUser')) || [],
    loginUser: JSON.parse(localStorage.getItem('LOGINUSER')) || {},//正在登录的用户
    loginedAllUser:JSON.parse(localStorage.getItem('LOGINEDALLUSER')) ||[]//存储登录过的用户
}
const mutations = {
    //更新新用户
    updateNewUser(state, newUser) {
        state.allUser.push(newUser);
        console.log('添加新用户成功:', state.allUser);
        // 👉 更新 localStorage
        localStorage.setItem('allUser', JSON.stringify(state.allUser));
    },
    //保存登录用户
    updateLoginUser(state, user) {
        state.loginUser = user
        console.log('打印保存的登录用户：');
        console.log(state.loginUser);
        //本地存储一下正在登录用户
         localStorage.setItem('LOGINUSER', JSON.stringify(state.loginUser))
        let exists=state.loginedAllUser.some(userItem=>userItem.userPhone==user.userPhone)
        if (!exists) {
            state.loginedAllUser.push(user)
            //把正在登录的用户本地存储到所有登录用户的数组中
            localStorage.setItem('LOGINEDALLUSER',JSON.stringify(state.loginedAllUser))
        }
       

    },
    //退出登录
    clearLoginUser(state){
        state.loginUser={}//更新vuex状态，触发视图响应式更新
        localStorage.removeItem("LOGINUSER");//清除本地缓存
        
    }
}

const actions = {
    //注册新用户
    async setRegister(context, regParams) {
        let res = await reqRegisterUser(regParams)
        console.log('打印一下传入的注册用户信息：');
        console.log(regParams);

        console.log(res);
        context.commit('updateNewUser', regParams)
    },
    //登录
    setLogin(context, loginParams) {
        context.commit('updateLoginUser', loginParams)
    }
}
const getters = {}
export default {
    namespaced: true,
    state, mutations, actions, getters
}